<!--
Date: 2025-08-13
Copyright (c) 2025 Industrial Software Feature Database
-->
<template>
  <div class="data-preview__main" v-loading="loading">
    <!-- <div v-if="pageType === 'EDIT' || pageType === 'ADD'" :style="{ height: pageType === 'EDIT' || pageType === 'ADD' ? '34px' : '0px' }">
      <el-button style="margin-bottom: 10px" type="primary" size="small" @click="saveMaterialData">保存数据</el-button>
    </div> -->

    <div v-loading="loading" class="data-preview__content" :style="{ height: pageType === 'EDIT' || pageType === 'ADD' ? 'calc(100% - 34px)' : '100%' }">
      <div class="treeClass" :style="{ width: leftWidth - 0.3 + '%' }">
        <el-card shadow="never" :class="['treeDiv', 'card-shadow', props.heightClass]" v-loading="loading">
          <!-- <el-tree
            ref="materialTree"
            :data="props.treeData"
            node-key="index"
            highlight-current
            :props="defaultProps"
            :default-expand-all="true"
            :current-node-key="currentChooseId"
            icon-class="el-icon-arrow-right"
            @node-click="treeSelect"
            @node-contextmenu="openMenu"
          >
            <template #default="{ data, node }">
              <el-tooltip v-if="data.data !== '查看更多'" :disabled="tooltipVisible" effect="dark" :content="data.data" placement="top">
                <span style="display: flex; align-items: center" @mouseover="handleNodeMouseOver">
                  <span class="sub_title"> {{ data.data }}</span>
                </span>
              </el-tooltip>
              <div v-else>
                <el-link style="font-size: 12px;" type="primary" size="mini">查看更多</el-link>
              </div>
            </template>
            :notInitRequest="props.notInitRequest"
            :treeResult="treeResult"
          </el-tree> -->
          <LinkFolder
            ref="linkFolderRef"
            :modelId="props.modelId"
            
            @getTreeNodeDetail="getNodeDetail"
            @saveData="saveMaterialData"
          />
          <!-- 自定义右键菜单 -->
          <div v-show="menuVisible" :style="menuStyle" class="custom-menu" ref="wrapper">
            <ul>
              <li v-if="showAddMenu" @click="handleMenuClick('add')">
                <el-button size="small" link type="primary" icon="DocumentCopy">复制</el-button>
              </li>
              <li @click="handleMenuClick('edit')">
                <el-button size="small" link type="primary" icon="Edit">编辑</el-button>
              </li>
              <li @click="handleMenuClick('delete')">
                <el-button size="small" link type="primary" icon="Delete">删除</el-button>
              </li>
            </ul>
          </div>
        </el-card>
      </div>
      <div class="resizer" @mousedown.prevent="startResize"></div>
      <div class="rightClass" :style="{ width: 100 - leftWidth + '%' }">
        <el-card shadow="never" :class="['right', 'card-shadow', props.heightClass]" style="overflow: auto; height: 100%;">
          <el-descriptions :column="1" border style="width: 100%" class="adaptive-column">
            <template v-for="(des, index) in columns">
              <el-descriptions-item
                v-if="des.type !== 'info'"
                :key="index"
                :label="des.chinese"
                label-align="right"
                align="center"
                width="150px"
                label-class-name="my-label"
                class-name="my-content"
              >
                <el-image v-if="des.type == 'image'" :src="des.data" fit="fit" />
                <div class="ellipsis-text" v-else>
                  <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="des.data"></el-input>
                  <span v-else>{{ des.data }}</span>
                </div>
              </el-descriptions-item>
            </template>
          </el-descriptions>
          <el-tabs v-if="!justShowForm" v-model="activeName" @tab-click="handleClick" style="width: 100%">
            <el-tab-pane v-for="(tab, index) in fields" :label="tab.chinese" :name="index" :key="index">
              <el-descriptions v-if="tab.type == 'object'" :column="1" border style="width: 100%" class="adaptive-column">
                <el-descriptions-item
                  v-for="(des, i) in tab.data"
                  :key="i"
                  :label="des.chinese + '(' + des.field + ')'"
                  label-align="right"
                  align="center"
                  width="150px"
                  label-class-name="my-label"
                  class-name="my-content"
                >
                  <!-- <el-image v-if="des.type == 'image'" :src="fileAbsolutePath() + des.data" fit="fit" /> -->
                  <template v-if="des.type == 'image'">
                    <el-link v-if="des.data" style="color: #409eff" size="small" type="primary" :href="des.data" target="_blank">
                      查看图片
                    </el-link>
                    <span v-else>暂无数据</span>
                    <el-button
                      style="margin-left: 20px"
                      v-if="pageType == 'EDIT' || pageType == 'ADD'"
                      size="small"
                      @click="updatePic([index, i], des)"
                      >重新上传</el-button
                    >
                  </template>

                  <template v-else>
                    <template v-if="des.type == 'object'">
                      <el-descriptions :column="1" border style="width: 100%" class="adaptive-column">
                        <el-descriptions-item
                          v-for="(des1, i1) in des.data"
                          :key="i1"
                          :label="des1.chinese + '(' + des1.field + ')'"
                          label-align="right"
                          align="center"
                          width="150px"
                          label-class-name="my-label"
                          class-name="my-content"
                        >
                          <!-- <el-image v-if="des1.type == 'image'" :src="fileAbsolutePath() + des1.data" fit="fit" /> -->
                          <!-- <template v-if="des1.type == 'image'">
                          <el-link :href="fileAbsolutePath() + des1.data" target="_blank">
                            <el-image :src="fileAbsolutePath() + des1.data" fit="fit" />
                          </el-link>
                        </template> -->
                          <template v-if="des1.type == 'image'">
                            <el-link
                              v-if="des1.data"
                              size="small"
                              style="color: #409eff"
                              type="primary"
                              :href="des1.data"
                              target="_blank"
                            >
                              查看图片
                            </el-link>
                            <span v-else>暂无数据</span>
                            <el-button
                              style="margin-left: 20px"
                              v-if="pageType == 'EDIT' || pageType == 'ADD'"
                              size="small"
                              @click="updatePic([index, i, i1], des1)"
                              >重新上传</el-button
                            >
                          </template>
                          <template v-else>
                            <template v-if="des1.type == 'object'"> </template>
                            <template v-else-if="des1.type == 'basic'">
                              <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="des1.data"></el-input>
                              <template v-else>{{ des1.data }}</template>
                            </template>
                          </template>
                        </el-descriptions-item>
                      </el-descriptions>
                    </template>
                    <template v-else-if="des.type == 'basic'">
                      <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="des.data"></el-input>
                      <template v-else>{{ des.data }}</template>
                    </template>
                    <template v-else-if="des.type == 'table'">
                      <el-table :data="des.data" border>
                        <el-table-column
                          v-for="(td, index) in filterTableColumns(des.data[0])"
                          :key="td._index"
                          :label="td.chinese + '(' + td.field + ')'"
                          :prop="td.field"
                          min-width="120"
                        >
                          <template #default="scope">
                            <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="scope.row[td._index]['data']"></el-input>
                            <span v-else>{{ scope.row[td._index]['data'] || '' }}</span>
                          </template>
                        </el-table-column>
                        <el-table-column v-if="pageType == 'EDIT' || pageType == 'ADD'" label="操作" align="center" width="100" fixed="right">
                          <template #default="scope">
                            <el-button size="small" link type="primary" @click="addExtensionInfo(des.data, scope.row)">添加</el-button>
                            <el-button size="small" link type="primary" @click="removeExtensionInfo(des.data, scope.$index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </template>
                  </template>
                </el-descriptions-item>
              </el-descriptions>
              <el-table v-else :data="tab.data" border>
                <el-table-column
                  v-for="(td, index) in filterTableColumns(tab.data[0])"
                  :key="td._index"
                  :label="td.chinese + '(' + td.field + ')'"
                  :prop="td.field"
                  min-width="150"
                >
                  <template #default="scope">
                    <el-input v-if="pageType == 'EDIT' || pageType == 'ADD'" v-model="scope.row[td._index]['data']"></el-input>
                    <span v-else>{{ scope.row[td._index]['data'] || '' }}</span>
                  </template>
                </el-table-column>
                <el-table-column v-if="pageType == 'EDIT' || pageType == 'ADD'" label="操作" align="center" width="100" fixed="right">
                  <template #default="scope">
                    <el-button size="small" link type="primary" @click="addExtensionInfo(tab.data, scope.row)">添加</el-button>
                    <el-button size="small" link type="primary" @click="removeExtensionInfo(tab.data, scope.$index)">删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-tab-pane>
          </el-tabs>
        </el-card>
      </div>
    </div>
    <UploadPicture
      v-if="importVisible"
      :importVisible="importVisible"
      :objectId="imageObjectId"
      :fieldPath="imageFieldPath"
      :tableName="tableName"
      :indexArr="indexArr"
      @handleEvent="handleEvent"
    />
  </div>
</template>

<script setup name="MaterialDataPreview">
import UploadPicture from './UploadPicture.vue';
import LinkFolder from './LinkFolder.vue';
import {
  getMaterialTreeNew,
  getMaterialNodeInfo,
  updateMaterialNodeData,
  deleteMaterialNodeData,
  addMaterialNodeData,
  getAssetDataList
} from '@/api/material/index.ts';
const emit = defineEmits(['handleEvent']);
const props = defineProps(['treeResult', 'notInitRequest', 'modelId', 'heightClass', 'canEdit', 'treeData', 'row', 'fieldList', 'height', 'tableName', 'currentChooseId', 'type']);
const loading = ref(false);
const linkFolderRef = ref();
const { proxy } = getCurrentInstance();
const nodeForm = ref({});
const columns = ref([]);
const fields = ref([]);
const currentChooseId = ref(null);
const treeData = ref([]);
const activeName = ref(0);
const rules = {};
const nodeData = ref({});
const nodeContent = ref(null);
const menuVisible = ref(false);
const wrapper = ref(null);
const pageType = ref('VIEW');
const justShowForm = ref(true);
const showAddMenu = ref(false);
const tooltipVisible = ref(false);
const importVisible = ref(false);
const imageObjectId = ref('');
const imageFieldPath = ref('');
const tableName = ref('');
const indexArr = ref([]);
const pageQuery = ref({
  pageNum1: 1,
  pageSize1: 50,
  pageNum2: 1,
  pageSize2: 50,
  pageNum3: 1,
  pageSize3: 50,
  pageNum4: 1,
  pageSize4: 50,
  pageNum5: 1,
  pageSize5: 50,
})
const total1 = ref(0)
const total2 = ref(0)
const total3 = ref(0)
const total4 = ref(0)
const total5 = ref(0)
const expandedRows = ref([])
const currentShowNode = ref(null)
const menuStyle = ref({
  left: 0,
  top: 0
});
const defaultProps = {
  children: 'children',
  label: 'chinese'
};
const leftWidth = ref(30);
let startX = 0;
let startWidth = 0;
const startResize = (event) => {
  startX = event.clientX;
  startWidth = leftWidth.value;
  window.addEventListener('mousemove', onResize);
  window.addEventListener('mouseup', stopResize);
};

const onResize = (event) => {
  const dx = event.clientX - startX;
  const newWidth = startWidth + (dx / window.innerWidth) * 100;
  leftWidth.value = Math.max(20, Math.min(80, newWidth)); // 限制宽度在10%到90%之间
};

const stopResize = () => {
  window.removeEventListener('mousemove', onResize);
  window.removeEventListener('mouseup', stopResize);
};

const updatePic = (arr, des) => {
  imageObjectId.value = des?.objectId;
  imageFieldPath.value = des?.fieldPath;
  tableName.value = nodeContent.value?.detail?.tableName;
  indexArr.value = arr;
  importVisible.value = true;
};
const handleEvent = (data) => {
  if (data.type == 'submit') {
    // 更新图片路径
    data.index.length == 2
      ? (fields.value[data.index[0]].data[data.index[1]].data = data.path)
      : (fields.value[data.index[0]].data[data.index[1]].data[data.index[2]].data = data.path);
  }
  importVisible.value = false;
};
const addExtensionInfo = (list, row) => {
  let _row = JSON.parse(JSON.stringify(row));
  _row.forEach((item, index) => {
    item.data = '';
  });
  list.push(_row);
};
const removeExtensionInfo = (list, index) => {
  list.splice(index, 1);
};
const filterTableColumns = (cols) => {
  // console.log('cols', cols)
  if (cols && cols.length > 0) {
    cols.forEach((item, index) => {
      item._index = index;
    });
    return cols.filter((col) => col.type !== 'info');
  } else {
    return [];
  }
};

// 右键点击
const openMenu = (event, data, node, element) => {
  if (pageType.value !== 'VIEW') {
    return;
  }
  if (!props?.canEdit) {
    return;
  }
  if (!data.children || data.children.length === 0) {
    justShowForm.value = false;
    showAddMenu.value = true;
  } else {
    justShowForm.value = true;
    showAddMenu.value = false;
  }
  // menuLevel.value = node.level;
  nodeContent.value = data;
  // 显示菜单
  menuVisible.value = true;
  // 阻止默认的右键菜单显示
  event.preventDefault();
  // 设置菜单的位置
  menuStyle.value.left = 200 + 'px';
  menuStyle.value.top = event.clientY - 122 + 'px';
};
const handleNodeMouseOver = (node) => {
  var target = node.target;
  let textLength = target.clientWidth;
  const nodeContent = target.closest('.el-tree-node__content');
  const containerWidth = nodeContent.clientWidth; // 获取包含 padding+border 的完整宽度
  console.log(textLength, containerWidth);
  if (textLength + 55 < containerWidth) {
    tooltipVisible.value = true;
  } else {
    tooltipVisible.value = false;
  }
};
const handleClick = (event) => {
  // 检查点击是否发生在外部
  if (wrapper.value && !wrapper.value.contains(event.target)) {
    menuVisible.value = false;
  }
};
const handleMenuClick = (type) => {
  if (type == 'delete') {
    ElMessageBox.confirm(`是否确认删除【${nodeContent.value?.data}】？`, `提示`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      if (nodeContent.value?.detail?.objectId == nodeData.value?.detail?.objectId) {
        fields.value = [];
        columns.value = [];
      }
      deleteMaterialNodeData({ tableName: nodeContent.value?.detail?.tableName, objectId: nodeContent.value?.detail?.objectId }).then((res) => {
        if (res.code == 200) {
          ElMessage({ showClose: true, message: '材料信息删除成功', type: 'success' });
          // getTreeData(nodeContent.value?.detail?.tableName);
          emit('handleEvent', { type: 'resetTree' });
        }
      });
    });
  } else if (type == 'edit' || type == 'add') {
    pageType.value = type == 'edit' ? 'EDIT' : 'ADD';
    getTreeInfo(nodeContent.value?.detail?.tableName, nodeContent.value?.detail?.objectId, 1);
  }
  menuVisible.value = false;
};
// tree选择事件
const treeSelect = (selected, node) => {
  // currentChooseId.value = selected.id;
  console.log(selected,node.nextSibling)
  menuVisible.value = false;
  if (!selected.children || selected.children.length == 0) {
    justShowForm.value = false;
  } else {
    justShowForm.value = true;
  }
  nodeData.value = selected;
  pageType.value = 'VIEW';
  getTreeInfo(selected?.detail?.tableName, selected?.detail?.objectId, 1);
};

const getNodeDetail = (info) => {
  // pageType.value = info.type;
  // justShowForm.value = false;
  // getTreeInfo(info.data?.tableName, info.data?.objectId, 1);
  const { type, data, name } = info;
  currentShowNode.value = info;
  if (type == 'DELETE') {
    ElMessageBox.confirm(`是否确认删除【${name}】？`, `提示`, {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      if (currentShowNode.value && currentShowNode.value.objectId == data.objectId) {
        fields.value = [];
        columns.value = [];
      }
      deleteMaterialNodeData({ tableName: data?.tableName, objectId: data?.objectId }).then((res) => {
        if (res.code == 200) {
          ElMessage({ showClose: true, message: '删除成功', type: 'success' });
          // emit('handleEvent', { type: 'resetTree' });
          linkFolderRef.value.refreshCurrent();
        }
      });
    });
  } else if (type == 'EDIT' || type == 'ADD' || type == "VIEW") {
    pageType.value = type;
    justShowForm.value = false;
    getTreeInfo(data?.tableName, data?.objectId, 1);
  } 
}

// 保存节点数据
const saveMaterialData = (info) => {
  const { type, data, name } = info;
  let params = {
    tableName: data.tableName,
    objectId: data?.objectId,
    data: [...fields.value, ...columns.value]
  };
  loading.value = true;
  let ApiInterface = pageType.value == 'ADD' ? addMaterialNodeData : updateMaterialNodeData;
  ApiInterface(params).then((res) => {
    res.code == 200 && ElMessage({ showClose: true, message: pageType.value == 'ADD' ? '新增成功' : '编辑成功', type: 'success' });
    // getTreeData(nodeContent.value?.detail?.tableName);
    linkFolderRef.value.refreshCurrent();
    loading.value = false;
  }).finally(() => {
    loading.value = false;
  });
};

const getTreeData = (tableName) => {
  loading.value = true;
  getMaterialTreeNew({
    tableName
  })
    .then((res) => {
      treeData.value = res.data;
      loading.value = false;
    })
    .finally(() => {
      loading.value = false;
    });
};
const getTreeInfo = (tableName, objectId, mergeMode) => {
  getMaterialNodeInfo({
    tableName,
    objectId,
    mergeMode
  }).then((res) => {
    fields.value = [];
    columns.value = [];
    fields.value = res.data.filter((item) => {
      return ['table', 'object'].includes(item.type);
    });
    columns.value = res.data.filter((item) => {
      return !['table', 'object'].includes(item.type);
    });
    if (pageType.value == 'ADD') {
      let _name = columns.value.find((item) => item.field == 'name');
      _name && (_name.data = '复制_' + _name.data);
    }
  });
};

onMounted(() => {
  window.addEventListener('click', handleClick);
});
onUnmounted(() => {
  window.removeEventListener('click', handleClick);
});
defineExpose({
  columns,
  fields
});
</script>

<style lang="scss" scoped>
/* 层级连接线样式 */
.level-line {
  position: absolute;
  top: 50%;
  height: 1px;
  width: 10px;
  background-color: #dcdfe6;
  transform: translateY(-50%);
}
.data-preview__main {
  // padding: 20px;
  overflow-y: auto;
  width: 100%;
  height: 100%;
  // height: calc(100vh - 148px);
  .el-table__expand-column {
    .cell {
      display: flex;
      align-items: center;
    }
  }
  .custom-menu {
    position: absolute;
    background-color: #fff;
    border: 1px solid #ebebeb;
    border-radius: 3px;
    width: 80px;
    z-index: 1000;
    font-size: 12px;
    ul {
      margin: 0;
      padding: 5px 0;
      list-style: none;
      font-size: 12px;
    }
    ul li {
      padding: 3px 15px;
      cursor: pointer;
      font-size: 12px;
      display: flex;
      align-items: center;
    }
    ul li:hover {
      background-color: #eee;
    }
  }
  .data-preview__content {
    display: flex;
    position: relative;
    .card-shadow {
      box-shadow:
        0 2px 4px rgba(0, 0, 0, 0.1),
        /* 主阴影 */ 0 8px 16px rgba(0, 0, 0, 0.05); /* 环境光 */
      transition: box-shadow 0.3s ease;
    }
    .treeClass {
      margin-right: 5px;
      height: 100%;
      overflow-y: auto;
      .treeDiv {
        flex: 0 0 300px;
        overflow-y: auto;
        &.search_result_height {
          max-height: calc(100vh - 150px);
        }
        &.map_result_height {
          max-height: calc(100vh - 285px);
        }
      }
    }
    .resizer {
      position: relative;
      width: 0.3%;
      background-color: #d9d9d9;
      cursor: ew-resize;
      border-radius: 5px;
    }
    .rightClass {
      margin-left: 5px;
      height: 100%;
      .right {
        flex: 1;
        overflow-y: auto;
        &.search_result_height {
          max-height: calc(100vh - 150px);
        }
        &.map_result_height {
          max-height: calc(100vh - 285px);
        }
      }
    }
  }
  .sub-model__main {
    width: 100%;
    ul,
    li {
      list-style: none;
      padding-left: 10px;
      width: 100%;
    }
    .row-even {
      background: #e9e6e6;
    }
    .row-odd {
      background: #fff;
    }
    &.padding50 {
      padding-left: 100px;
    }
    .field-list__item {
      // display: flex;
      .field-row {
        padding: 5px 0 5px 10px;
      }
      .field-name {
        color: #409eff;
        width: 150px;
      }
      span {
        width: 150px;
        display: inline-block;
        margin-right: 10px;
        font-size: 12px;
        white-space: break-spaces;
        word-wrap: break-word;
        height: auto;
      }
    }
    .title {
      font-size: 18px;
      font-weight: 500;
      color: rgba(0, 0, 0, 0.85);
      &::before {
        content: '';
        display: inline-block;
        width: 3px;
        height: 16px;
        margin-right: 5px;
        background-color: #409eff;
        vertical-align: middle;
        margin-top: -3px;
      }
    }
  }
  // .ellipsis-text {
  //   white-space: nowrap; /* 不换行 */
  //   overflow: hidden; /* 隐藏溢出内容 */
  //   text-overflow: ellipsis; /* 显示省略号 */
  //   max-width: 600px; /* 设置最大宽度 */
  // }
  // .adaptive-column .el-descriptions__item {
  //   flex: 1; /* 让每个 item 自适应宽度 */
  // }
}
</style>
